<template>
  <div>
  <ConfigProvider :locale="zhCN">
    <a-card :bordered="false">
      <!-- 查询区域 -->
      <div class="table-page-search-wrapper">
        <a-form @keyup.enter="search">
          <a-row :gutter="24">
            <a-col :span="4">
              <a-form-item label="客户名称">
                <a-input allowClear v-model="queryParams.name"></a-input>
              </a-form-item>
            </a-col>
            <a-col :span="5" :offset="1">
              <a-form-item label="月份">
                  <a-month-picker
                      placeholder="选择月份"
                      format="YYYY-MM"
                      :defaultValue="lastMonth"
                      @change="handleMonthChange">
                    <template #suffixIcon>
                      <SmileOutlined />
                    </template>
                  </a-month-picker>
              </a-form-item>
            </a-col>
            <a-col :span="3">
              <a-form-item label="分组统计">
                <a-select allowClear v-model:value="queryParams.statsType" @change="handleStatsTypeChange">
                  <a-select-option value="id_client">按客户名</a-select-option>
                  <a-select-option value="id_trade_partner">按贸易方</a-select-option>
                  <a-select-option value="group_type">按客户组</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="2" :offset="1">
              <a-form-item>
                <a-button @click.prevent="search" type="default" :loading="loading">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 查询区域-END -->
      <!-- table区域-begin -->
      <div>
        <a-table
            size="middle"
            bordered
            :rowKey="queryParams.statsType"
            :columns="filterColumns(columns)"
            :customHeaderRow="headerClick(columns,0)"
            :rowClassName="setRowStyle()"
            :dataSource="dataSource"
            :rowSelection="rowSelection"
            :customRow="rowClick"
            @change="(pagination) => { handleTableChange('summary', pagination) }"
            :pagination="ipaginations.summary"
        >
          <template #money="{ text }">￥{{text||0}}</template>
        </a-table>
      </div>
      <div>
        <a-card title="关联记录" :size="size">
          <a-card title="入帐记录" :size="size">
            <template #extra>
              <a href="#">新增</a>
            </template>
            <a-table
                ref="tableBillChecked"
                :size="size"
                bordered
                rowKey="id"
                :columns="filterColumns(columnsBillChecked)"
                :customHeaderRow="headerClick(columnsBillChecked,1)"
                :dataSource="dataSourceDetail"
                @change="(pagination,filter,sorter) => { handleTableChange('accounted', pagination, sorter) }"
                :pagination="ipaginations.accounted"
                :loading="loading"
            >
              <!-- 使用 v-slot 语法 -->
              <template #total_amount="{ text, record }">
                <a-tooltip :class="{'ant-table-row-selected rowBeExec': !queryParams.id_trade_partner}" placement="left"
                           :title="feeTip(record)" :get-popup-container="getPopupContainer">
                  <span>{{ text }}</span>
                </a-tooltip>
              </template>
              <template #action="{ text, record }">
                <a @click="() => view(record, '入帐明细')">详细</a>
                <a-divider type="vertical"/>
                <a-dropdown>
                  <a class="ant-dropdown-link">更多 <DownOutlined/></a>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item>
                        <a-popconfirm title="确定删除吗?" @confirm="() => delProfit(record)">
                          <a>删除</a>
                        </a-popconfirm>
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </template>
            </a-table>
          </a-card>
          <a-card title="支付记录" :size="size" :style="{ marginTop: '16px' }">
            <template #extra>
              <a href="#">新增</a>
            </template>
            <a-table
                :size="size"
                bordered
                rowKey="id"
                :columns="filterColumns(columnsPayment)"
                :customHeaderRow="headerClick(columnsPayment,2)"
                :dataSource="dataSourcePayment"
                @change="(pagination,filter,sorter) => { handleTableChange('payment', pagination, sorter) }"
                :pagination="ipaginations.payment"
                :loading="subLoading"
            >
              <template #total_amount="{ text, record }">
                <a-tooltip :class="{'ant-table-row-selected rowBeExec': !queryParams.id_trade_partner}" placement="left"
                           :title="feeTip(record)" :get-popup-container="getPopupContainer">
                  <span>{{ text }}</span>
                </a-tooltip>
              </template>
              <template #action="{ text, record }" >
                <a @click="() => edit(record)">编辑</a>
                <a-divider type="vertical"/>
                <a-dropdown>
                  <a class="ant-dropdown-link">更多 <DownOutlined/></a>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item>
                        <a-popconfirm title="确定删除吗?" @confirm="() => delPayment(record)">
                          <a>删除</a>
                        </a-popconfirm>
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </template>
            </a-table>
          </a-card>
          <a-card title="开票记录" :size="size" :style="{ marginTop: '16px' }">
            <template #extra>
              <a href="#">新增</a>
            </template>
            <a-table
                ref="tableInvoice"
                :size="size"
                bordered
                rowKey="id"
                :columns="filterColumns(columnsInvoice)"
                :customHeaderRow="headerClick(columnsInvoice,3)"
                :dataSource="dataSourceInvoice"
                @change="(pagination,filter,sorter) => { handleTableChange('invoice', pagination, sorter) }"
                :pagination="ipaginations.invoice"
                :loading="subLoading"
            >
              <template #total_amount="{ text, record }">
                <a-tooltip :class="{'ant-table-row-selected rowBeExec': !queryParams.id_trade_partner}" placement="left"
                           :title="feeTip(record)" :get-popup-container="getPopupContainer">
                  <span>{{ text }}</span>
                </a-tooltip>
              </template>
              <template #action="{ text, record }" v-show="action_show(record)">
                <a @click="() => view(record, '发票明细')">详细</a>
                <a-divider type="vertical"/>
                <a-dropdown>
                  <a class="ant-dropdown-link">更多 <DownOutlined/></a>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item>
                        <a-popconfirm title="确定删除吗?" @confirm="() => delInvoice(record)">
                          <a>删除</a>
                        </a-popconfirm>
                      </a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </template>
            </a-table>
          </a-card>
        </a-card>
      </div>

  <!--    <PaymentAddModal ref="paymentAddModal" :size="size" @sync="search" :invoices="dataSourceInvoice" :id_client="id_client"></PaymentAddModal>-->
  <!--    <InvoiceAddModal ref="inVoiceAddModal" :size="size" @sync="search" :companies="checkBillStore.companies" :id_client="id_client"></InvoiceAddModal>-->
  <!--    <DetailModal  ref="detailModal" :size="size" :dictProperties="checkBillStore.dictObj"  :columns="columnsTmp" :editable="false"></DetailModal>-->
  <!--    <column-config :visible="columncfgVisible[0]" @close="() => columnCinfigClose(0)" id="clientBill" :columns="columns"></column-config>-->
  <!--    <column-config :visible="columncfgVisible[1]" @close="() => columnCinfigClose(1)" id="tableBillChecked" :columns="columnsBillChecked"></column-config>-->
  <!--    <column-config :visible="columncfgVisible[2]" @close="() => columnCinfigClose(2)" id="tablePayment" :columns="columnsPayment"></column-config>-->
  <!--    <column-config :visible="columncfgVisible[3]" @close="() => columnCinfigClose(3)" id="tableInvoice" :columns="columnsInvoice"></column-config>-->
    </a-card>
  </ConfigProvider>
  </div>
</template>


<script setup>
import { ref, computed, watch, onMounted } from 'vue';
import { accAdd, accMinus, commonConf, filterColumns, headerClick,
        values2Texts } from '@/utils/my';
import PaymentAddModal from '@/views/modules/PaymentAddModal.vue';
// import InvoiceAddModal from '@/views/modules/InvoiceAddModal.vue';
import { postAction, getAction } from '@/utils/request';
import DetailModal from "@/views/modules/basicModal/DetailModal.vue";
import useCheckBillStore from "@/store/modules/checkBill.js";
import useUserStore from '@/store/modules/user'
import { message } from 'ant-design-vue';
import { ConfigProvider } from 'ant-design-vue';
import zhCN from 'ant-design-vue/lib/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import _ from 'lodash'

// 设置当前页面的dayjs语言为中文
dayjs.locale('zh-cn');

/* store */
const checkBillStore = useCheckBillStore()
const currentUser = useUserStore()
checkBillStore.getMyCompanies()
checkBillStore.getPortsAndClient()
checkBillStore.getTradePartner()
/* data */
// simple vars
// 获取当前日期的上一个月
const lastMonth = dayjs().subtract(1, 'month');
const size = "small"
//响应式数据
const show = ref({
  search: false
});

const columnsTmp = ref([]);
// 表头
const columns = ref([
  {
    title: '客户名称', align: 'center', dataIndex: 'id_client'
  },{
    title: '总单数', align: 'right', dataIndex: 'total',
    sorter: (a, b) =>  (a.total||0) - (b.total||0),
  },{
    title: '收入', align: 'right', dataIndex: 'income',
    sorter: (a, b) =>  (a.income||0) - (b.income||0),
    slots: { customRender: 'money' }
  },{
    title: '支出', align: 'right', dataIndex: 'expenditure',
    sorter: (a, b) =>  (a.expenditure||0) - (b.expenditure||0),
    slots: { customRender: 'money' }
  },{
    title: '利润总额', align: 'right', dataIndex: 'profit',
    sorter: (a, b) =>  (a.profit||0) - (b.profit||0),
    slots: { customRender: 'money' }
  },{
    title: '已支付总额', align: 'right', dataIndex: 'paid_amount',
    sorter: (a, b) =>  (a['paid_amount']||0) - (b['paid_amount']||0),
    slots: { customRender: 'money' }
  },{
    title: '应收总额', align: 'right', dataIndex: 'unpaid_amount',
    sorter: (a, b) =>  (a['unpaid_amount']||0) - (b['unpaid_amount']||0),
    slots: { customRender: 'money' }
  },{
    title: '已开票金额', align: 'right', dataIndex: 'invoice_amount',
    sorter: (a, b) =>  a.invoice_amount - b.invoice_amount,
    slots: { customRender: 'money' }
  }
]);
const columnsBillChecked = ref([
  {
    title: '入帐日期', align: 'center', dataIndex: 'accounted_date',
    sorter: (a, b) =>  new Date(a.accounted_date)-new Date(b.accounted_date),
    customRender: function({text: t}) {
      return t && dayjs(t).format("YYYY-MM-DD")
    }
  },{
    title: '入帐公司', align: 'center', width: 230, dataIndex: 'id_company',
  },{
    title: '总单数', align: 'right', dataIndex: 'total'
  },{
    title: '利润总额', align: 'right', dataIndex: 'profit',
    sorter: (a,b) => a.profit - b.profit,
    slots: { customRender: 'money' }
  },{
    title: '收入', align: 'right', dataIndex: 'income',
    slots: { customRender: 'money' }
  },{
    title: '支出', align: 'right', dataIndex: 'expenditure',
    slots: { customRender: 'money' }
  },{
    title: '创建时间', align: 'center', dataIndex: 'create_time', sorter: true,
    customRender: function({text: t}) {
      return t && dayjs(t).format("YYYY-MM-DD")
    }
  },{
    title: '创建人', align: 'center', dataIndex: 'create_by'
  },{
    title: '操作', align: 'center', dataIndex: 'action', width: 120, fixed: 'right',
    slots: { customRender: 'action' }
  }
]);
const columnsPayment = ref([
  {
    title: '支付ID号', align: 'center', width: 180, dataIndex: 'id',
  },
  {
    title: '支付日期', align: 'center', dataIndex: 'payment_date', sorter: true,
    customRender: function({text: t}) {
      return t && dayjs(t).format("YYYY-MM-DD")
    }
  },{
    title: '所属月份', align: 'center', width: 180, dataIndex: 'bill_month',
  },{
    title: '关联发票号', align: 'center', width: 180, dataIndex: 'invoice_nos',
    customRender: (({text:t})=> {
        return t.join(',')
    })
  },{
    title: '支付金额', align: 'right', sorter: true,
    dataIndex: 'amount'
  },{
    title: '备注', align: 'right', dataIndex: 'memo'
  },{
    title: '创建时间', align: 'center', dataIndex: 'create_time',
    customRender: function({text: t}) {
      return t && dayjs(t).format("YYYY-MM-DD")
    }
  },{
    title: '创建人', align: 'center', dataIndex: 'create_by'
  },{
    title: '操作', align: 'center', dataIndex: 'action', width: 120, fixed: 'right',
    slots: { customRender: 'action' }
  }
]);
const columnsInvoice = ref([
  {
    title: '开票日期', width: 120, align: 'center', dataIndex: 'invoice_date', sorter: true,
    customRender: function(t, r, index) {
      return t && dayjs(t).format("YYYY-MM-DD")
    }
  },{
    title: '发票号', align: 'center', dataIndex: 'invoice_no'
  },{
    title: '发票金额', align: 'right', dataIndex: 'invoice_amount', sorter: true,
  },{
    title: '总单数', align: 'right', dataIndex: 'total'
  },{
    title: '利润总额', align: 'right', dataIndex: 'profit',
    slots: { customRender: 'money' }
  },{
    title: '收入', align: 'right', dataIndex: 'income',
    slots: { customRender: 'money' }
  },{
    title: '支出', align: 'right', dataIndex: 'expenditure',
    slots: { customRender: 'money' }
  },{
    title: '所属支付', align: 'center', width: 100, dataIndex: 'id_payment',
  },{
    title: '所属公司', align: 'center', width: 210, dataIndex: 'id_company',
  },{
    title: '备注', align: 'right', dataIndex: 'memo'
  },{
    title: '创建时间', align: 'center', dataIndex: 'create_time', sorter: true,
    customRender: function({text: t}) {
      return t && dayjs(t).format("YYYY-MM-DD")
    }
  },{
    title: '创建人', align: 'center', dataIndex: 'create_by'
  },{
    title: '操作', align: 'center', dataIndex: 'action', width: 120, fixed: 'right',
    slots: { customRender: 'action' }
  }
]);
const columnsBill = ref([
  {
    title: '帐单日期', align: 'center', width: 100, dataIndex: 'bill_date',
    sorter: (a, b) =>  new Date(a.bill_date)-new Date(b.bill_date),
    customRender: function(t, r, index) {
      if(t==='totallabel') return  "合 计："
      return t && dayjs(t).format("YYYY-MM-DD")
    }
  },{
    title: '帐单类型', align: 'center', width: 40, dataIndex: 'bill_type',
    customRender: function(t, r, index) {
      //t-值，r-记录，index-记录下的索引
      return t===1?'收入':'支出';
    }
  },{
    title: '贸易方', align: 'center', width: 80, dataIndex: 'id_trade_partner',
  },{
    title: '帐单号', align: 'center', width: 120, dataIndex: 'bill_no',
  },{
    title: '航班号', align: 'center', width: 70, dataIndex: 'flight_no',
  },{
    title: '始发港', align: 'center', width: 60, dataIndex: 'departure_port',
  },{
    title: '目的港', align: 'center', width: 60, dataIndex: 'destination_port',
  },{
    title: '件数', align: 'center', width: 70, dataIndex: 'articles',
  },{
    title: '重量', align: 'center', width: 70, dataIndex: 'weight',
  },{
    title: '计费重量', align: 'center', width: 70, dataIndex: 'weight_for_fee',
  },{
    title: '单价', align: 'center', width: 60, dataIndex: 'unit_price',
  },{
    title: '总金额', align: 'center', width: 75, dataIndex: 'total_amount',
    sorter: (a, b) => a.total_amount - b.total_amount,
  },{
    title: '创建时间', align: 'center', dataIndex: 'create_time', sorter: true
  },{
    title: '创建人', align: 'center', dataIndex: 'create_by'
  }
]);
const table = ref({
  selectedRowKeys: []
});
const url = {
  getDataBySql: '/sys/getDataBySql',
  asyncDataBySql: '/sys/asyncDataBySql',
  get_statistics_for_clients: '/yg/get_statistics_for_clients',
  get_statistics_for_invoices_payments: '/yg/get_statistics_for_invoices_payments',
};

const feeColumns = ref([]);
const feeItemTitles = ref(undefined);
const feeTipStr = ref({});
const queryParams = ref({
  name: undefined,
  id_client: undefined,
  statsType: 'id_client',
  bill_month: '',
  accounted_date: []
});
const loading = ref(false);
const subLoading = ref(false);
const dataSource = ref([])
const filterKey = ref(undefined);
const dataSourceDetail = ref([]);
const dataSourceInvoice = ref([]);
const dataSourcePayment = ref([]);
const paymentRecords = ref([]);
const ports = ref([]);
const exportable = ref(false);
const ipaginations = reactive({
  summary: {
    current: 1,
    pageSize: 10,
    pageSizeOptions: ['10', '20', '30','50','100'],
    showTotal: (total, range) => {
      return range[0] + "-" + range[1] + " 共" + total + "条"
    },
    showQuickJumper: true,
    showSizeChanger: true,
    total: 0
  },
  accounted: {
    current: 1,
    pageSize: 10,
    pageSizeOptions: ['10', '20', '30','50','100'],
    showTotal: (total, range) => {
      return range[0] + "-" + range[1] + " 共" + total + "条"
    },
    showQuickJumper: true,
    showSizeChanger: true,
    total: 0
  },
  payment: {
    current: 1,
    pageSize: 10,
    pageSizeOptions: ['10', '20', '30','50','100'],
    showTotal: (total, range) => {
      return range[0] + "-" + range[1] + " 共" + total + "条"
    },
    showQuickJumper: true,
    showSizeChanger: true,
    total: 0
  },
  invoice: {
    current: 1,
    pageSize: 10,
    pageSizeOptions: ['10', '20', '30','50','100'],
    showTotal: (total, range) => {
      return range[0] + "-" + range[1] + " 共" + total + "条"
    },
    showQuickJumper: true,
    showSizeChanger: true,
    total: 0
  }
});
const columncfgVisible = ref([false, false, false, false]);
/* watch */
// 计算属性
const rowSelection = computed(() => {
  return {
    type: 'radio',
    selectedRowKeys: table.value.selectedRowKeys,
    onChange:  (selectedRowKeys, selectedRows) => {
        console.log(`selectedRowKeys: ${selectedRowKeys[0]}`, 'selectedRows: ', selectedRows);
        table.value.selectedRowKeys[0] = selectedRowKeys[0];
        filterKey.value = selectedRowKeys[0]; // 会触发 dataSourceDetailFiltered 计算属性
        console.error("queryParams.value.statsType:", queryParams.value.statsType)
        console.error("selectedRowKeys[0]:", selectedRowKeys[0])
        queryParams.value.id_client = queryParams.value.statsType==='id_client'?selectedRowKeys[0]:undefined;
        queryList(true)
        getInvoicePayment()
        console.error("params:", JSON.stringify(queryParams.value),queryParams.value.statsType==='id_client')
    }
  };
});


const scroll = computed(() => {
  let length = 1270;
  if (queryParams.value.id_trade_partner) {
    feeColumns.value.forEach((fc) => {
      length += parseInt(fc.width);
    });
    length += 50;
  }
  return { x: length };
});

/* method */
const handleTableChange = ( section, source, sorter ) => {
  //console.error("section:", section)
  Object.assign(ipaginations[section], source, _.pick(sorter,['field','order']))
  if(['summary','accounted'].includes(section))queryList();
  getInvoicePayment()
}

const handleStatsTypeChange = (value) => {
  columns.value.shift()
  if (value === 'id_client'){
      columns.value.unshift(
          {title: '客户名称', align: 'center', dataIndex: 'name'},
      )
  }else if (value === 'id_trade_partner'){
      columns.value.unshift(
          {title: '贸易方名称', align: 'center', dataIndex: 'trader_name'},
      )
  }else{
      columns.value.unshift(
          {title: '客户组名称', align: 'center', dataIndex: 'group_type'},
      )
  }
  //console.error("columns", JSON.stringify(columns.value))
  dataSource.value = [];dataSourceDetail.value = [];
  dataSourcePayment.value = [];dataSourceInvoice.value = [];
  queryParams.value.id_client = undefined
  filterKey.value = undefined
}
// 处理月份选择变化
const handleMonthChange = (date, dateString) => {
  console.log(date, dateString);
  queryParams.value.bill_month = dateString
  if (!date) {
    queryParams.value.accounted_date = [];
    return;
  }
  // 计算当月第一天和最后一天
  const year = date.year();
  const month = date.month(); // moment的月份是0-based (0-11)
  // 当月第一天
  const startOfMonth = date.clone().startOf('month');
  // 当月最后一天
  const endOfMonth = date.clone().endOf('month');
  // 存储日期区间
  queryParams.value.accounted_date = [
      startOfMonth.format('YYYY-MM-DD HH:mm:ss'),
      endOfMonth.format('YYYY-MM-DD HH:mm:ss')
  ]
};



const rowClick = (record, index) => {
  let row = {
    on: {
      click: () => {
        let keys = [record.id];
        table.value.selectedRowKeys = keys;
        let rows = [record];
        table.selectionRows = rows;
      }
    }
  };
  return row;
};

const getProfitdetail = async (id) => {
  let sql = `select * from YG_billChecked_record where id_client=${id} order by accounted_date desc`;
  const res = await postAction(url.getDataBySql, { sql });
  if (res && res.success) {
    dataSourceDetail.value = res.result;
    ipaginations.accounted.total = res.result.length;
  }
};
const getDictLabel = (table, value) => {
  return dictOptions[table].find(d => d.value === value)?.label || '';
};

const getPopupContainer = (trigger) => {
  return trigger.parentElement;
};
const groupObj = (v) => {
  if((v === undefined) || (v === null)) return '合 计';
  switch(queryParams.value.group){
    case 'id_trade_partner':
      return checkBillStore.tradePartnerObj[v].name? `${checkBillStore.tradePartnerObj[v].group_type}-${checkBillStore.tradePartnerObj[v].name}` : v;
    case 'id_company':
      return checkBillStore.companyObj && checkBillStore.companyObj[v]||v;
    case 'status':
      return checkBillStore.dictObj.status[`${v}`]||v;
    default:
      return "合 计";
  }
}

const getFeeSql = (id) => {
  return `select code,amount,ft.name from YG_CheckingBill_fee_view f join YG_FeeType ft on id_CheckingBill=${id} and ft.id=f.id_FeeType;`;
};
const delProfit = async (record) => {
  let sql1 = `update YG_CheckingBill set id_accounted=null,status='0' where id_accounted=${record.id}`;
  let res1 = await syncData(sql1);
  if (!(res1 && res1.success)) {
    message.error(res1.message);
    return;
  }
  let sql2 = `delete from YG_billChecked_record where id = ${record.id}`;
  let res2 = await syncData(sql2);
  if (res2 && res2.success) {
    message.success("删除成功！");
    let res3 = await updateMain();
    if (!(res3 && res3.success)) message.success("更新数据失败！");
    search();
  } else {
    message.error(res2.message);
  }
};
const delPayment = async (record) => {
  let sql1 = `delete from YG_payment where id = ${record.id}`;
  let res1 = await syncData(sql1);
  let res2;
  if (res1 && res1.success) {
    res2 = await updateMain();
  } else {
    message.error(res1.message);
  }
  if (res2 && res2.success) {
    message.success("删除成功！");
    search();
  } else {
    message.error(res2.message);
  }
};
const delInvoice = async (record) => {
  let sql1 = `update YG_CheckingBill set id_invoiced=null,status=case when id_accounted is not null then '1' else '0' end where id_invoiced=${record.id}`;
  let res1 = await syncData(sql1);
  if (!(res1 && res1.success)) {
    message.error(res1.message);
    return;
  }
  let sql2 = `delete from YG_invoice where id = ${record.id}`;
  let res2 = await syncData(sql2);
  let res3;
  if (res2 && res2.success) {
    res3 = await updateMain();
  } else {
    message.error(res2.message);
  }
  if (res3 && res3.success) {
    message.success("删除成功！");
    search();
  } else {
    message.error(res3.message);
  }
};
const edit = async (record) => {
  paymentaddModal.value.edit(record);
};
const syncData = async (sql) => {
  return postAction(url.getDataBySql, { sql });
};
const view = async (record, title) => {
  let detailTable, sql;
  if (title === '入帐明细') {
    sql = `select * from YG_CheckingBill where id_accounted = ${record.id}`;
    columnsTmp.value = columnsBillChecked.value;
  } else {
    sql = `select * from YG_CheckingBill where id_invoiced = ${record.id}`;
    columnsTmp.value = columnsInvoice.value;
  }
  columnsTmp.value.forEach((c) => c.is_show = 1);
  let res = await syncData(sql);
  if (res && res.success) {
    detailTable = {
      columns: columnsBill.value,
      data: res.result,
      title: "关联对帐单"
    };
  }
  let tmp = { ...record };
  checkBillStore.dictObj.id_company = {};
  checkBillStore.dictObj.id_trade_partner = {};
  checkBillStore.dictObj['id_company'][tmp['id_company']] = checkBillStore.companyObj[tmp['id_company']].title;
  if (tmp['accounted_date']) tmp['accounted_date'] = moment(tmp['accounted_date']).format("YYYY-MM-DD");
  if (tmp['invoice_date']) tmp['invoice_date'] = moment(tmp['invoice_date']).format("YYYY-MM-DD");
  detailModal.value.detail(tmp, [], detailTable, title);
};

const setRowStyle = (flag, id) => {
  return (record, index, i) => {
    let type = table.value.selectedRowKeys.indexOf(record.id) === -1 ? 'executed' : 'rowBeExec';
    let style = `ant-table-row-selected ${type}`;
    return style;
  };
};

const getInvoicePayment = async () => {
  subLoading.value = true
  if (filterKey.value && !queryParams.value.id_client){
    dataSourceInvoice.value = [];
    ipaginations.invoice.total = 0
    dataSourcePayment.value =[];
    ipaginations.payment.total = 0
  }else{
    let res = await postAction(url.get_statistics_for_invoices_payments, { ...queryParams.value,
        invoice: {..._.pick(ipaginations.invoice, ['current', 'pageSize', 'order', 'field'])},
        payment: {..._.pick(ipaginations.payment, ['current', 'pageSize', 'order', 'field'])},
    });
    if (res && res.success) {
      let { invoices, payments } = res.data
      dataSourceInvoice.value = invoices.rows;
      ipaginations.invoice.total = invoices.count
      dataSourcePayment.value = payments.rows;
      ipaginations.payment.total = payments.count
    } else {
      message.error(res.message);
    }
  }
  subLoading.value = false
};

const queryList = async (summary_no_fresh) => {
  // console.error("columns:",JSON.stringify(filterColumns(columns.value)))
  // console.error("params", JSON.stringify(queryParams.value));
  if(!summary_no_fresh)dataSource.value = [];
  dataSourceDetail.value = [];
  ipaginations.summary.total = 0;
  loading.value = true
  const res = await getAction(url.get_statistics_for_clients, {...queryParams.value, filterKey: filterKey.value,
      ..._.pick(ipaginations.accounted,['current', 'pageSize', 'order', 'field'])})
  if (res.success) {
    const {clients, checkingBills} = res.data;
    if(!summary_no_fresh) {
      dataSource.value = clients.rows;
      ipaginations.summary.total = clients.count || 0;
    }
    dataSourceDetail.value = checkingBills.rows;
    ipaginations.accounted.total = checkingBills.count || 0;
  }
  loading.value = false;
  console.error(JSON.stringify(ipaginations))
};

const setDefault = () => {
  ipaginations.summary.current = 1;
  ipaginations.accounted.current = 1
  ipaginations.invoice.current = 1
  ipaginations.payment.current = 1
  dataSource.value = [];
  dataSourceDetail.value = [];
  dataSourceInvoice.value = [];
  dataSourcePayment.value = [];
  table.value.selectedRowKeys = [];
  filterKey.value = ''
  queryParams.value.id_client = undefined
};

const search = () => {
  setDefault()
  queryList();
  getInvoicePayment()
};

const addPayment = () => {
  paymentaddModal.value.add();
};
const addInvoice = () => {
  inVoiceaddModal.value.add();
  //console.error(JSON.stringify(this.dictOptions.companies))
};
const sumUp = (obj, statsItems = [], labelField) => {
  let total = {};
  total[labelField] = 'totallabel';
  statsItems.forEach(s => {
    total[s] = 0;
  });
  obj.forEach(d => {
    statsItems.forEach(s => {
      total[s] = accAdd(total[s], d[s]);
    });
  });
  if (obj && obj[obj.length - 1] && obj[obj.length - 1][labelField] !== "totallabel") obj.push(total);
};



const columnCinfigClose = (index) => {
  columncfgVisible.value[index] = false;
};

// 这里假设 accAdd 函数在其他地方定义
// 如果没有定义，需要添加其实现
// const accAdd = (arg1, arg2) => { ... };

// 监听
// watch(() => table.value.selectedRowKeys, (newValue, oldValue) => {
//   getProfitdetail(newValue[0]);
//   id_client.value = newValue[0];
//   getPayment();
//   getInvoice();
// }, { deep: true });

// 挂载时
onMounted(() => {
  handleMonthChange(lastMonth, lastMonth.format("YYYY-MM"))
});

// 组件引用
const tableBillChecked = ref(null);
const paymentaddModal = ref(null);
const inVoiceaddModal = ref(null);
const detailModal = ref(null);
</script>

<style scoped>
.ant-table-bordered .ant-table-tbody > tr > td,th{
  padding:4px !important;
}
.ant-popover-inner-content {
  padding:4px !important;
}
.underline {
  font-weight: bold;
  color: red;
}
</style>